<!--
 * @Author: duliang thinktanker@163.com
 * @Date: 2024-07-06 10:03:09
 * @LastEditors: duliang thinktanker@163.com
 * @LastEditTime: 2024-07-13 18:17:51
 * @FilePath: \dul-text-recognition\templates\phone.html
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Send Video Frame</title>
    <style>
        /* 通过CSS限制视频尺寸 */
        video {
            width: 100%;
            /* 根据容器宽度调整 */
            height: auto;
            /* 保持宽高比 */
            max-width: 640px;
            /* 视频最大宽度 */
            max-height: 480px;
            /* 视频最大高度 */
            object-fit: contain;
            /* 保持视频内容完整显示 */
        }
    </style>
    <script>
        //全局变量
        let phone_uuid;
        // 读取cookie的函数
        function getCookie(name) {
            let cookieArr = document.cookie.split(";");

            for (let i = 0; i < cookieArr.length; i++) {
                let cookiePair = cookieArr[i].split("=");

                /* Removing whitespace at the beginning of the cookie name
                and compare it with the given string */
                if (name == cookiePair[0].trim()) {
                    // Decode the cookie value and return
                    return decodeURIComponent(cookiePair[1]);
                }
            }

            // Return null if the cookie wasn't found
            return null;
        }
        // 将UUID保存到cookie，这里设置cookie名为uuid，有效期为7天（秒为单位）
        function setCookie(name, value, days) {
            let expires = "";
            if (days) {
                const date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                expires = "; expires=" + date.toUTCString();
            }
            document.cookie = name + "=" + (value || "") + expires + "; path=/";
        }

        function generateUUID() {
            return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
                (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
            );
        }
        window.onload = function () {
            phone_uuid = getCookie('uuid');
            if (phone_uuid) { } else {
                phone_uuid = generateUUID();
                setCookie('uuid', phone_uuid, 30);
            }
            //alert(phone_uuid);
        }
        function about() {
            document.getElementById('uuid').innerText = phone_uuid;
            alert(phone_uuid);
        }
    </script>
</head>

<body>
    <button id="about">关于</button>
    <video id="video" autoplay muted></video>
    <button id="start">开始视频</button>
    <div id="uuid"></div>
    <div id="responseMessage"></div>
    <script>
        async function startVideo() {
            const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" } });
            document.getElementById('video').srcObject = stream;
            setInterval(() => {
                captureAndSendFrame()
            }, 500);
        }
        document.getElementById('start').addEventListener('click', startVideo);
        document.getElementById('about').addEventListener('click', about);
        function captureAndSendFrame() {
            const canvas = document.createElement('canvas');
            canvas.width = document.getElementById('video').videoWidth * 4;
            //canvas.width = 1080;
            canvas.height = document.getElementById('video').videoHeight * 4;
            //canvas.height =1920;
            const ctx = canvas.getContext('2d');
            ctx.drawImage(document.getElementById('video'), 0, 0, canvas.width, canvas.height);

            const dataUrl = canvas.toDataURL('image/jpeg'); // 转换为JPEG格式的Base64

            fetch('/capture', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ imageBase64: dataUrl, uuid: phone_uuid })
            })
                .then(response => response.json())
                .then(data => displayServerResponse(data)) // 调用新函数显示服务器响应
                //.then(data => console.log(data))
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('responseMessage').innerText = "An error occurred!";
                });
        }

        function displayServerResponse(result) {
            // 在这里处理并显示服务器返回的信息
            console.log("Server Response:", result);
            // 如果你想在页面上显示一个消息，可以找到一个元素（比如一个<div>）并更新其内容
            // 假设你有这样一个元素：<div id="responseMessage"></div>
            document.getElementById('responseMessage').innerText = result.message;
        }
    </script>
</body>

</html>